<template>
  <div class="receiveNetWapper">
    <!-- 非子账号导入 -->
    <rj-modal
      :title="$t('executionLog.msg')"
      :visible="noSubImport"
      :maskClosable="false"
      :cancelText="$t('receiveNet.cancel')"
      :okText="$t('receiveNet.ok')"
      @ok="importNoSubNet"
      :width="500"
      @cancel="cancelSubNet"
    >
      <div class="hint">{{ $t('receiveNet.issue') }}</div>
      <div class="netInfoWapper">
        <a-form-model
          :model="form"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          class="fromEle"
          ref="importFrom"
        >
          <a-form-model-item
            :label="$t('gwAuthentication.networkName')"
            labelAlign="right"
            prop="groupName"
          >
            <a-input
              class="inputStyle"
              autocomplete="off"
              :disabled="true"
              v-model="form.groupName"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('receiveNet.sharer')"
            labelAlign="right"
            prop="userName"
          >
            <a-input
              class="inputStyle"
              autocomplete="off"
              :disabled="true"
              v-model="form.userName"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('receiveNet.tenant')"
            labelAlign="right"
            prop="tenantName"
            :rules="[
              {
                required: true,
                message: $t('receiveNet.enter'),
              },
              {
                validator: checkTenantName,
                trigger: 'change',
              },
            ]"
          >
            <a-input
              class="inputStyle"
              autocomplete="off"
              v-model="form.tenantName"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('receiveNet.remark')"
            labelAlign="right"
            prop="remark"
            :rules="[
              {
                validator: checkRemark,
                trigger: 'change',
              },
            ]"
          >
            <a-textarea
              v-model="form.remark"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-model-item>
        </a-form-model>

        <div class="hintFoot">
          <icon-font type="ic-notice" class="iconHint" />{{
            $t('receiveNet.tips')
          }}
        </div>
      </div>
    </rj-modal>

    <!-- 子账号导入 -->
    <rj-modal
      :title="$t('executionLog.msg')"
      :visible="subImport"
      :maskClosable="false"
      :cancelText="$t('receiveNet.disagree')"
      :okText="$t('receiveNet.agree')"
      @ok="importSubNet"
      :width="500"
      @cancel="cancelSubNet"
    >
      <div class="importTxt">
        {{ $t('receiveNet.tip1')
        }}<span style="color: #2b6afd">{{ shareInfo.tenantName }}</span
        >{{ $t('receiveNet.tip2')
        }}<span style="color: #2b6afd">{{ shareInfo.groupName }}</span
        >{{ $t('receiveNet.tip3') }}
      </div>
    </rj-modal>
    <!-- 导入成功提示 -->
    <rj-modal
      title=""
      :visible="successModal"
      :maskClosable="false"
      :width="400"
      :footer="null"
      @cancel="cancelSuceessHint"
    >
      <div class="shareSuccessHint">
        <p class="projectName">
          {{ $t('receiveNet.project') }}{{ this.shareInfo.groupName
          }}{{ $t('receiveNet.success') }}
        </p>
        <div style="margin-bottom: 15px">
          {{ receiveTip }}
        </div>
        <img class="hintImg" :src="tipImgUrl" alt="" />
      </div>
      <div class="successModalFooter">
        <a-space>
          <a-button @click="cancelSuceessHint">{{
            $t('common.cancel')
          }}</a-button>
          <a-button type="primary" @click="goToProject">{{
            $t('receiveNet.goTo')
          }}</a-button>
        </a-space>
      </div>
    </rj-modal>
  </div>
</template>
<script>
import { maccApi, requestHttp, ValiDateTools } from '@utils/index';
import { mapState } from 'vuex';
export default {
  name: 'receiveNet',
  props: {
    shareCode: {
      type: String,
    },
  },

  data() {
    return {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      noSubImport: false,
      subImport: false,
      form: {
        userName: undefined,
        tenantName: undefined,
        groupName: undefined,
        remark: undefined,
      },
      shareType: undefined,
      shareInfo: undefined,
      successModal: false,
      tipImgUrl: '@assets/images/common/changShareNetHint.png',
      tipTxt: this.$t('receiveNet.tips2'),
    };
  },

  components: {},

  computed: {
    ...mapState('Theme', ['theme']),
  },

  async mounted() {
    if (this.theme == 'RUIYI_V2') {
      this.tipTxt = this.$t('common.receivePrjTip');
      this.tipImgUrl =
        process.env.VUE_APP_COMMON_IMG_PATH + '/common/changShareNetHint.png';
    }

    console.log('shareCode', this.shareCode);
    const result = await this.getShareNetInfo();
    if (!result) return;
  },

  watch: {},

  methods: {
    //获取分享网络信息
    async getShareNetInfo() {
      const res = await requestHttp({
        api: `${maccApi.GET_NET_SHART_API}?share_code=${this.shareCode}`,
        method: 'GET',
      });

      if (res.code != 0) {
        this.$message.error(res.msg || this.$t('receiveNet.failed3'));
        return false;
      }
      this.shareInfo = res;
      this.shareType = res.userGroupType;
      if (res && res.userGroupType == 'NORMAL') {
        //已经是子账号
        this.showSubImportNet(res);
      } else {
        //非子账号导入
        this.showNoSubImportNet(res);
      }

      return true;
    },

    //已是子账号，接受父账号分享的网络
    showSubImportNet(netInfo) {
      console.log('netInfo', netInfo);
      this.subImport = true;
    },

    //不是子账号，接受分享的网络
    showNoSubImportNet(netInfo) {
      const { userName, groupName, tenantName } = netInfo;
      this.form.userName = userName;
      this.form.groupName = groupName;
      this.form.tenantName = tenantName;
      this.form = { ...this.form };
      this.noSubImport = true;
    },

    //立即导入（非子账号）
    importNoSubNet() {
      this.$refs.importFrom.validate(async (valid) => {
        if (valid) {
          await this.saveImport();
        } else {
          return false;
        }
      });
    },

    //立即导入（子账号）
    async importSubNet() {
      await this.saveImport();
    },

    async saveImport() {
      const { userGroupType } = this.shareInfo;
      const { code, msg } = await requestHttp({
        api: `${maccApi.IMPORT_SHARE_NETWORK}`,
        method: 'POST',
        params: {},
        querys: {
          shareCode: this.shareCode,
        },
      });

      if (code == 0 || code == 2038) {
        //2038是用户已经有该网络权限
        if (userGroupType != 'NORMAL') {
          const resultArr = await Promise.all([
            this.changeTenantName(),
            this.changeNetWorkRemark(),
          ]);
          const allSuccess = resultArr.every((it) => {
            return it;
          });

          if (!allSuccess) return;
        }
        this.noSubImport = false;
        this.subImport = false;
        this.successModal = true;
        return;
      }
      if (code == '2041') {
        this.$message.info(this.$t('receiveNet.shareFailTip1'));
      } else if (code == '2051') {
        this.$message.info(this.$t('receiveNet.shareFailTip2'));
      } else if (code == '2042') {
        this.$message.info(this.$t('receiveNet.shareFailTip3'));
      } else {
        this.$message.error(msg || this.$t('receiveNet.shareFailTip4'));
      }
    },

    //修改租户名称
    async changeTenantName() {
      const { tenantId } = this.shareInfo;
      const { tenantName } = this.form;
      const { code, msg = this.$t('receiveNet.failed2') } = await requestHttp({
        api: `${maccApi.SET_ORG_ALIAS_API.replace('{tenantId}', tenantId)}`,
        method: 'PUT',
        params: {},
        querys: {
          alias: tenantName,
        },
      });

      if (code != 0) {
        this.$message.error(msg);
        return false;
      }

      return true;
    },

    //修改项目备注
    async changeNetWorkRemark() {
      const { tenantId, groupId } = this.shareInfo;
      const { remark } = this.form;
      // const remark = this.form.getFieldValue('remark');
      if (!remark) return true;
      const { code, msg = this.$t('receiveNet.failed') } = await requestHttp({
        api: maccApi.SET_NET_WORK_REMARK_API,
        method: 'PUT',
        params: {
          tenantId,
          groupId: groupId,
          remark,
        },
      });

      if (code != 0) {
        this.$message.error(msg);
        return false;
      }

      return true;
    },

    //取消导入
    cancelSubNet() {
      this.noSubImport = false;
      this.subImport = false;
    },

    //校验组织名称
    checkTenantName(r, v, cb) {
      const { result, msg } = ValiDateTools.checkStrLength(v);
      if (!result) {
        cb(new Error(msg));
      }

      if (v.toUpperCase() == 'ROOT') {
        cb(new Error(this.$t('receiveNet.noRoot')));
      }

      cb();
    },

    //校验项目备注
    checkRemark(r, v, cb) {
      if (v) {
        const { result, msg } = ValiDateTools.checkStrLength(v, 1, 128);
        if (!result) {
          cb(new Error(msg));
        }

        if (v.toUpperCase() == 'ROOT') {
          cb(new Error(this.$t('receiveNet.noRoot')));
        }
        cb();
      } else {
        cb();
      }
    },

    //关闭成功提示弹窗
    cancelSuceessHint() {
      this.successModal = false;
    },

    //点击立即前往
    async goToProject() {
      const { tenantId, groupId } = this.shareInfo;
      if (this.theme == 'RUIYI_V2') {
        this.$router.push('monitor_project_workbarn_menu');
      } else {
        this.$router.push('monitor_overview_networkdetails_menu');
      }
      this.successModal = false;
      if (this.shareInfo.userGroupType != 'NORMAL') {
        this.$store.commit('User/SET_CURRENT_IS_SHARE_MODE', true); //设置为受邀托管模式
      }
      this.$store.commit('Group/SET_GROUPID', groupId);
    },
  },
};
</script>

<style lang="less" scoped>
.netInfoWapper {
  border: 1px dashed #ddd;
  margin-top: 15px;
  .fromEle {
    padding: 10px;
  }
}
.hintFoot {
  color: #f60;
  background-color: #ffffe1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 30px;
  .iconHint {
    font-size: 14px;
    margin-right: 3px;
    color: #666;
  }
}

.shareSuccessHint {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;

  .projectName {
    color: #018903;
    font-size: 20px;
  }
  .hintImg {
    width: 90%;
    height: auto;
  }
}
.successModalFooter {
  margin-top: 20px;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
}
</style>
